package com.lxc.graduation.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lxc.graduation.utils.JWTUtils;
import com.lxc.graduation.utils.JsonData;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author: ck
 * @Description:
 * @Date: Create in 22:14 2021/2/9
 */
@Slf4j
public class LoginInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        try {
            String accessToken = request.getHeader("token");
            if (accessToken == null) {
                accessToken = request.getParameter("token");
            }
            if (StringUtils.isNotBlank(accessToken)) {
                Claims claim = JWTUtils.checkJWT(accessToken);
                if (claim == null) {
                    sendJsonMessage(response, JsonData.buildError("登录过期，重新登录"));
                    return false;

                }
                Integer id = (Integer) claim.get("id");
                String name = (String) claim.get("name");
                request.setAttribute("id", id);
                request.setAttribute("name", name);

                return true;


            }
        }catch (Exception e)
        {
            log.info("token校验异常");
        }

        sendJsonMessage(response, JsonData.buildError("登录过期，重新登录"));
        return false;
    }

    /**
     * 响应json数据给前端
     * @param response
     * @param obj
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj){

        try{
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(objectMapper.writeValueAsString(obj));
            writer.close();
            response.flushBuffer();
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
